import React, { useReducer, useContext, createContext } from "react";
import { ErrorBoundary } from "./components/ErrorBoundary";

const CounterContext = createContext(undefined);

function counterReducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "reset":
      return { count: 0 };
    default:
      return state;
  }
}

function CounterProvider({ children }) {
  const [state, dispatch] = useReducer(counterReducer, { count: 0 });
  return (
    <CounterContext.Provider value={{ state, dispatch }}>
      {children}
    </CounterContext.Provider>
  );
}

function useCounter() {
  const context = useContext(CounterContext);
  if (!context)
    throw new Error("useCounter must be used within a CounterProvider");
  return context;
}

function CounterDisplay() {
  const { state } = useCounter();
  return <div>{state.count}</div>;
}

function CounterButtons() {
  const { dispatch } = useCounter();
  return (
    <div>
      <button onClick={() => dispatch({ type: "increment" })}>+1</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-1</button>
      <button onClick={() => dispatch({ type: "reset" })}>重置</button>
    </div>
  );
}

function App() {
  return (
    <ErrorBoundary>
      <CounterProvider>
        <CounterDisplay />
        <CounterButtons />
      </CounterProvider>
    </ErrorBoundary>
  );
}

export default App;
